package com.ljt.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;

public class MD5Utils {

	
	public static String encrypt(String org)
	{
        MessageDigest md;
		try {
			md = MessageDigest.getInstance("MD5");
	        md.update(org.getBytes());//update处理  
	        byte [] encrypted = md.digest();//调用该方法完成计算 
	        return ByteUtils.Byte2Hex(encrypted);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		
		return null;
	}
	/**
	 * MD5加密
	 * @param source
	 * @return
	 */
	public static String MD5(byte[] source) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(source);
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString();
//            System.out.println("MD5(" + sourceStr + ",32) = " + result);
//            System.out.println("MD5(" + sourceStr + ",16) = " + buf.toString().substring(8, 24));
        } catch (NoSuchAlgorithmException e) {
        	e.printStackTrace();
            System.out.println(e);
        }
        return result.toUpperCase();
   }

	/**
	 * 解密
	 * @param key
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String base64Decode(String key) throws UnsupportedEncodingException, Base64DecodingException{
		return new String(Base64.decode(key), "UTF-8");
	}
	/**
	 * 加密
	 * @param str
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public static String base64Encode(String str) throws UnsupportedEncodingException{
		String a=Base64.encode(str.getBytes("UTF-8"));
		return a;
	}
}
